import sys

from PyQt6.QtNetwork import QHostAddress
from PyQt6.QtWidgets import *

from ClientHandlerThread import *


class MyServer(QTcpServer):
    connectionList = []

    def __init__(self, parent=None):
        super().__init__(parent)
        self.listen(QHostAddress("127.0.0.1"), 6666)
        self.newConnection.connect(self.handle_new_connection)

    def handle_new_connection(self):
        print('connect')
        client_socket = self.nextPendingConnection()
        client_handler_thread = ClientHandlerThread(client_socket)
        client_handler_thread.finished.connect(self.remove_connection)
        self.connectionList.append(client_handler_thread)
        client_handler_thread.start()

    def remove_connection(self):
        print('remove')
        thread = self.sender()
        self.connectionList.remove(thread)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    server = MyServer()
    sys.exit(app.exec())
